import { getWeathers, getWeatherDailyHistory } from '@ray-js/ray';
import { useDevId } from '@ray-js/panel-sdk/lib/hooks/useDevId';
import { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';

export interface Weather {
  conditionNum: number;
  thigh: number;
  tlow: number;
  [key: string]: any;
}

const mockData = [
  {
    conditionNum: 120,
    thigh: '35.00',
    localDate: 1759593600000,
    tlow: '24.00',
    date: '2025-10-05',
  },
  {
    conditionNum: 120,
    thigh: '36.00',
    localDate: 1759680000000,
    tlow: '25.00',
    date: '2025-10-06',
  },
  {
    conditionNum: 121,
    thigh: '32.00',
    localDate: 1759766400000,
    tlow: '26.00',
    date: '2025-10-07',
  },
  {
    conditionNum: 120,
    thigh: '30.00',
    localDate: 1759852800000,
    tlow: '24.00',
    date: '2025-10-08',
  },
  {
    conditionNum: 120,
    thigh: '30.00',
    localDate: 1759939200000,
    tlow: '22.00',
    date: '2025-10-09',
  },
  {
    conditionNum: 120,
    thigh: '32.00',
    localDate: 1760025600000,
    tlow: '23.00',
    date: '2025-10-10',
  },
  {
    windSpeed: '2.4',
    so2: 6,
    sunRise: '2025-10-11 05:54',
    pressure: 1009,
    sunRiseTimeStamp: 1760133240000,
    uvi: 5,
    pop: 0,
    tlow: 23,
    sunSet: '2025-10-11 17:29',
    no2: 11,
    pm25: 9,
    conditionNum: '120',
    windLevel: 1,
    condIconUrl: 'https://images.tuyacn.com/smart/weather/icon2/120.png',
    sunSetTimeStamp: 1760174940000,
    quality: '优',
    humidity: 76,
    pm10: 29,
    o3: 66,
    qualityLevel: 2,
    condition: '晴',
    realFeel: 35,
    qpf: 0,
    sunset: '2025-10-11 17:29',
    thigh: 35,
    windDir: 'NE',
    aqi: 29,
    co: 1,
    zoneId: 'Asia/Shanghai',
    temp: 30,
    sunrise: '2025-10-11 05:54',
  },
];

export const useWeekWeather = () => {
  const { deviceId } = useDevId();
  console.log(`🚀 ~ deviceId:`, deviceId);
  const [weekWeathers, setWeekWeathers] = useState<Weather[]>([]);
  const [loading, setLoading] = useState(false);

  const weekNumberRef = useRef<string>(dayjs().format('d'));

  // @ts-ignore
  useEffect(async () => {
    setLoading(true);
    const weekNumber = weekNumberRef.current;
    const nextLength = 7 - Number(weekNumber);

    const nextWeathers = await getWeathers({
      devId: deviceId,
      dataRange: 7,
    });

    const currWeekNextWeathers = nextWeathers.weathers.slice(0, nextLength > 0 ? nextLength : 7);

    const preLength = +weekNumber === 7 ? 0 : Number(weekNumber);

    const startTime = dayjs().subtract(7, 'day').valueOf();

    const endTime = dayjs().valueOf();

    const prevWeathers = await getWeatherDailyHistory({
      devId: deviceId,
      weatherFieldNames: 'conditionNum,thigh,tlow',
      beginTime: startTime,
      endTime: endTime,
    })
      .then(res => {
        console.log('🚀 ~ useWeekWeather ~ res:', res);

        return res || {};
      })
      .catch(err => {
        console.log('🚀 ~ useWeekWeather ~ err:', err);
        return {};
      });

    console.log('🚀 ~ useWeekWeather ~ prevWeathers:', { prevWeathers, startTime, endTime });

    const sortedPrevWeathers = Object.values(prevWeathers || {})
      .sort((a, b) => b.localDate - a.localDate)
      .slice(0, preLength)
      .reverse();

    const totalWeathers = [...sortedPrevWeathers, ...currWeekNextWeathers];

    setLoading(false);

    setWeekWeathers(totalWeathers as unknown as Weather[]);
  }, []);

  return {
    weekWeathers: weekWeathers?.length === 7 ? weekWeathers : mockData,
    weekNumber: weekNumberRef.current,
    loading,
  };
};
